<?php
/**
 * PhpStorm.
 * User: Jay
 * Date: 2018/11/2
 */

namespace AdminBundle\Services;


use AdminBundle\Controller\AdminController;

class Menu extends AdminController
{
    /**
     * 获取菜单
     * 目前仅支持二级分类，三级以上分类需重写该方法
     *
     * @param $userId
     * @return mixed
     */
    public function getMenus($userId)
    {
        // TODO 缓存数据
        $data = self::$conn->fetchAll('SELECT * FROM menu');

        $permissions = $this->getPermissionMenus($userId);

        $permissionMenus = [];
        foreach ($data as $k => $v) {
            if (!$v['is_bind_permission'] || isset($permissions[$v['id']]) || $this->isSuperAdmin($this->getUserId())) {
                $permissionMenus[] = $v['id'];
            }

            if ($v['url']) {
                $data[$k]['url'] = $this->generateUrl($v['url'], $v['url_params'] ? unserialize($v['url_params']) : []);
            }
        }

        // php5.5+
        $allMenus = array_column($data, null, 'id');
        $menus = [];
        foreach ($permissionMenus as $id) {
            $menu = [
                'id' => $id,
                'title' => $allMenus[$id]['title'],
                'url' => $allMenus[$id]['url'],
                'icon' => $allMenus[$id]['icon'],
                'tag' => $allMenus[$id]['tag'],
                'sort_order' => $allMenus[$id]['sort_order']
            ];

            if ($allMenus[$id]['parent_id']) {
                if (in_array($allMenus[$id]['parent_id'], $permissionMenus)) {
                    $menus[$allMenus[$id]['parent_id']]['children'][] = $menu;
                }
            } else {
                // 该菜单是顶级菜单
                if (isset($menus[$id])) {
                    $menus[$id] = array_merge($menus[$id], $menu);
                } else {
                    $menus[$id] = $menu;
                }
            }
        }

        return $this->menuSort($menus);
    }

    /**
     * 菜单排序
     *
     * 按照sort_order从小到大排列
     *
     * @param $menus
     * @return mixed
     */
    private function menuSort($menus)
    {
        $sort = array_column($menus, 'sort_order');
        array_multisort($sort, SORT_ASC, $menus);

        foreach ($menus as $k => $v) {
            if (isset($v['children'])) {
                $menus[$k]['children'] = $this->menuSort($v['children']);
            }
        }

        return $menus;
    }

    private function getPermissionMenus($userId)
    {
        $permissions = $this->getPermissionsByUser($userId);

        $permissionMenus = [];

        foreach ($permissions as $v) {
            $permissionMenus[$v->menuId] = true;
        }

        return $permissionMenus;
    }
}